package views.components;

import com.vaadin.addon.jpacontainer.EntityItem;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.data.Property;
import com.vaadin.data.util.converter.Converter.ConversionException;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import com.vaadin.ui.VerticalLayout;

import config.Parameters;
import dao.interfaces.IBase;
/**
 * Clase que crea un comboBox en totes les ocurrencies de myClass en la BD
 *
 */
@SuppressWarnings("serial")
public class SelectorEntitats extends CustomField<IBase> {

	private ComboBox comboBox;
	private Class<IBase> myClass;
	private JPAContainer<IBase> jpaContainer;

	public SelectorEntitats(Class<IBase> myClass) {

		this.myClass = myClass;
		comboBox = new ComboBox();

		jpaContainer = JPAContainerFactory.make(myClass,
				Parameters.DB_DATA_SOURCE);

		comboBox.setContainerDataSource(jpaContainer);
		comboBox.setItemCaptionPropertyId("description");
		comboBox.setImmediate(true);
	}

	@Override
	protected Component initContent() {
		VerticalLayout root = new VerticalLayout();
		comboBox.setCaption(myClass.getSimpleName());
		root.addComponent(comboBox);
		return root;
	}

	@Override
	public Class<IBase> getType() {
		return myClass;
	}

	@Override
	public IBase getValue() {

		Object value = comboBox.getValue();
		EntityItem<IBase> item = jpaContainer.getItem(value);
		IBase entity = item != null ? item.getEntity() : null;

		return entity;
	}

	@Override
	public void setValue(IBase newFieldValue)
			throws com.vaadin.data.Property.ReadOnlyException,
			ConversionException {
		super.setValue(newFieldValue);
		setIbase(newFieldValue);
	}

	private void setIbase(IBase ibase) {
		comboBox.setValue(ibase != null ? ibase.getId() : null);
	}

	@Override
	public void setReadOnly(boolean readOnly) {
		comboBox.setReadOnly(readOnly);
	}
	
	@Override
	public Property<Object> getPropertyDataSource() {
		
		Property<Object> propertyDataSource = super.getPropertyDataSource();
		Object value = getValue();
		propertyDataSource.setValue(value);

		return propertyDataSource;
	}

	@Override
	public void setPropertyDataSource(Property newDataSource) {
		super.setPropertyDataSource(newDataSource);
		setIbase((IBase) newDataSource.getValue());
	}

}
